package config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * redis哨兵集群的连接配置
 *
 * @Date: 2024/07/26/8:01
 */
@Configuration
@PropertySource("classpath:application.properties")
public class RedisSentinelConfig {
    @Value("${redis.sentinels}")
    private String hosts;

    @Value("${redis.sentinel.master}")
    private String master;

    @Value("${redis.sentinel.timeout}")
    private int timeout;

    @Value("${redis.sentinel.maxIdle}")
    private int maxIdle;

    @Value("${redis.sentinel.maxWaitMillis}")
    private int maxWaitMillis;

    @Value("${redis.sentinel.blockWhenExhausted}")
    private Boolean blockWhenExhausted;

    @Value("${redis.sentinel.jmxEnabled}")
    private Boolean jmxEnabled;


    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(jmxEnabled);

        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);

        return jedisPoolConfig;
    }

    @Bean
    public JedisSentinelPool jedisSentinelPoolFactory() {
        if (StrUtil.isBlank(hosts)) {
            throw new RuntimeException("请配置redis哨兵集群的节点");
        }

        List<String> hostList = Arrays.asList(hosts.split(","));
        if (CollectionUtil.isEmpty(hostList)) {
            throw new RuntimeException("hostList is empty");
        }

        Set<String> hostSet = new HashSet<>(hostList);
        return new JedisSentinelPool(master, hostSet, jedisPoolConfig(), timeout);
    }
}
